<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
websocket Demo---- user000 <br />
<input id="text" type="text" />
<p>duifang's id</p>
<input id="people" type="text" />

<p>group's id</p>
<input id="team" type="text" />
<p>you's id</p>
<input id="me" type="text" />


<button onclick="send()"> Send </button>
<button  onclick="closeWebSocket()"> Close </button>
<button onclick="openwebsocket()">begin cent</button>
<div id="message">   </div>

<script type="text/javascript">
    //判断当前浏览器是否支持WebSocket



    function openwebsocket() {

        //前端限制一下
        if('WebSocket' in window && window.websocket==undefined){
            var websocket = new WebSocket("ws://localhost:8080/webSocket/"+document.getElementById("me").value);
            //var websocket = new WebSocket("ws://47.117.0.64:8888/ssmbuild/webSocket/"+document.getElementById("me").value);
            window.websocket=websocket;
            console.log("link success")

            websocket.onerror = function(){
                setMessageInnerHTML("error");
            };


            websocket.onopen = function(event){
                setMessageInnerHTML("open");
            }
            console.log("-----")

            websocket.onmessage = function(event){
                alert(event.data)
                setMessageInnerHTML(event.data);
            }


            websocket.onclose = function(){
                setMessageInnerHTML("close");
            }

            //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
            window.onbeforeunload = function(){
                websocket.close();
            }
        }else{
            alert('Not support websocket')
        }
    }



    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML){
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    //关闭连接
    function closeWebSocket(){
        websocket.close();
    }

    //发送消息
    function send(){
        var message={
            myid:document.getElementById("me").value,
            groupid:document.getElementById("team").value,
            userid:document.getElementById("people").value,
            message:document.getElementById("text").value
        }
        websocket.send(JSON.stringify(message));
    }
    //群发功能
    function sendall() {
        var message=document.getElementById('team').value;
        message=message
    }
</script>

</body>
</html>